package com.summer.campussct.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.summer.campussct.mapper.RolePermissionMapper;
import com.summer.campussct.pojo.Permission;
import com.summer.campussct.mapper.PermissionMapper;
import com.summer.campussct.pojo.RolePermission;
import com.summer.campussct.pojo.dto.RestResult;
import com.summer.campussct.service.IPermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.summer.campussct.utils.UserIdHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 权限表（菜单表） 服务实现类
 * </p>
 *
 * @author Mr.Chen
 * @since 2024-05-12
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Resource
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public RestResult getList() {
        List<Permission> list = this.list(new LambdaQueryWrapper<Permission>()
                .select(Permission::getId, Permission::getCode, Permission::getDescription, Permission::getPid, Permission::getName)
                .eq(Permission::getStatus, 1));
        return RestResult.success(list);
    }

    @Override
    public RestResult addPermission(Permission permission) {
        permission.setCreateUserId(UserIdHolder.getId());
        permission.setUpdateUserId(UserIdHolder.getId());
        if (!this.save(permission)) {
            throw new RuntimeException("新增权限失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult modifyPermission(Permission permission) {
        permission.setUpdateUserId(UserIdHolder.getId());
        if (!this.updateById(permission)) {
            throw new RuntimeException("修改权限失败");
        }
        return RestResult.success();
    }

    @Override
    public RestResult getDetails(long id) {
        Permission one = this.getOne(new LambdaQueryWrapper<Permission>()
                .select(Permission::getId, Permission::getCode, Permission::getName, Permission::getDescription)
                .eq(Permission::getId, id));
        return RestResult.success(one);
    }

    @Override
    public RestResult deleteDetails(long id) {
        // 删除权限表
        if (!this.removeById(id)) {
            throw new RuntimeException("删除权限失败");
        }

        // 删除关联表
        int delete = rolePermissionMapper.delete(new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getPid, id));
        if (delete == 0){
            throw new RuntimeException("删除关联表失败");
        }
        return RestResult.success();
    }
}
